//
// Created by 崔世强 on 2018/3/8.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation

class PropertyObserver<T> {
    
    var closure: ((T?) -> Void)!
    weak var reference: AnyObject?
    
}

class PropertyObservable<T:Equatable> {
    
    var value: T? {
        set(newValue) {
            if newValue == nil && value == nil {
                return
            }
            self._value = newValue
            self.notify()
            self.after?(self._value)
        }
        
        get {
            return self._value
        }
    }
    
    private var _value: T?
    private var observers = [PropertyObserver<T>]()
    var after: ((T?) -> Void)?
    
    func notify() {
        observers.forEach {
            if $0.reference != nil {
                $0.closure(self.value)
            }
        }
    }
    
    func bindObserver(observer: AnyObject, closure: @escaping ((T?) -> Void)) {
        self.clean()
        
        let _observer = PropertyObserver<T>()
        _observer.closure = closure
        _observer.reference = observer
        
        self.observers.append(_observer)
    }
    
    func clean() {
        self.observers = self.observers.filter {
            return $0.reference != nil
        }
    }
}
